package com.weme.common.util

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.util.Log
import com.weme.common.manager.SocketConnectManager

/**
 * 手机网络监听
 *
 * @author 
 */
class ConnectivityReceiver : BroadcastReceiver() {

    private val TAG = this::class.java.simpleName

    override fun onReceive(context: Context?, intent: Intent?) {
        val connectivityManager =
            context?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager

        if (connectivityManager != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val network = connectivityManager.activeNetwork
                val capabilities = connectivityManager.getNetworkCapabilities(network)
                if (capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
                    // 网络连接
                    Log.e(TAG, "手机有网络")
                    SocketConnectManager.startReConnect()
                } else {
                    // 网络断开
                   // SocketConnectManager.disConnect()
                    Log.e(TAG, "手机无网络")
                }
            } else {
                // 对于Android M以下版本，可以继续使用老的方法
                val networkInfo = connectivityManager.activeNetworkInfo
                if (networkInfo != null && networkInfo.isConnected) {
                    // 网络连接
                    Log.e(TAG, "手机有网络")
                    SocketConnectManager.startReConnect()
                } else {
                    // 网络断开
                 //   SocketConnectManager.disConnect()
                    Log.e(TAG, "手机无网络")
                }
            }
        }
    }
}
